package com.senseauto.surfacemediacodec;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.UiModeManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import android.widget.Toast;

import com.senseauto.surfacemediacodec.Constants;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import gxa.car.utils.VehicleHelper;

/**
 * 之前的MediaCodec+ 摄像头的byte[] 录制视频，在车机上有颜色变色的问题，没找到解决方案(手机和平板正常)
 * 网上说有一种可以用surface+MediaCodec的方式来解决这种变色的问题，特意写了一个例子 需要了解OpenGLES+FBO离屏显示
 */
//本界面主要申请权限
public class MainActivity extends AppCompatActivity {
    String TAG = "MainActivity";
    private String[] permissions = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    private List<String> mPermissionList = new ArrayList<>();
    private int PERMISSION_REQUEST_CODE = 100;
    private boolean permissionGetted;
    private boolean hasAllPermission() {
        mPermissionList.clear();
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        return mPermissionList.size() <= 0;

    }
    private ActivityResultLauncher<String[]> permissionRequest = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), granteds -> {
        boolean parsed = true;
        Log.i(TAG, "permission result : class->" + granteds.getClass());
        for (String key : granteds.keySet()) {
            parsed &= granteds.get(key);
        }
        permissionGetted = parsed;
        if (parsed) {
            //openCamera();
            Log.e(TAG, "可以打开摄像头了！");
        }
    });
    /*@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }

            if (hasPermissionDismiss) {
                Toast.makeText(this, "请授予必要权限", Toast.LENGTH_SHORT).show();
            } else {
                printCameraInfo();
            }
        }
    }*/


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //用来判断是车机系统还是平板上运行的，自动切换不同的摄像头id
        int carType = Constants.getCurrentCarType();
        Log.e(TAG, "carType="+carType);

        //下面的是之前的写法
        /*if (!hasAllPermission()) {
            ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST_CODE);
        } else { //第一次赋值过权限后，第二次打开界面
            //startCamera();
            printCameraInfo();
        }*/
        requestPermission();

        findViewById(R.id.camera1).setOnClickListener(v->{
            startActivity(new Intent(this, RecordActivity.class));
        });

    }
    private void requestPermission() {
        for (String str : permissions) {
            if (ContextCompat.checkSelfPermission(this, str) != PackageManager.PERMISSION_GRANTED) {
                permissionRequest.launch(permissions);
                return;
            }
        }
        permissionGetted = true;
        Log.e(TAG, "requestPermission->permissionGetted="+permissionGetted);
    }
    private void printCameraInfo() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            Log.e(TAG, "Camera manager.getCameraIdList()=>" + (cameraManager.getCameraIdList() == null ? -1 : cameraManager.getCameraIdList().length));
            for (String cameraId : cameraManager.getCameraIdList()) {
                Log.e(TAG, "Camera for 循环里：cameraId=" + cameraId);
                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
                StreamConfigurationMap configMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                Size[] sizes = configMap.getOutputSizes(SurfaceTexture.class);
                // 打印输出所有分辨率信息
                for (Size size : sizes) {
                    Log.e(TAG, "Camera " + cameraId + " supported resolution: " + size.getWidth() + "x" + size.getHeight());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e(TAG, "onRequestPermissionsResult: rc=" + requestCode + "\n" + Arrays.toString(permissions) + "\n" + Arrays.toString(grantResults));
        boolean enable = true;
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                enable = false;
                break;
            }
        }
        permissionGetted = enable;
        Log.e(TAG, "permissionGetted=" + permissionGetted + " requestCode=" + requestCode);
        if (enable) {
            //afterPermissionInitCamera();
            Log.e(TAG, "onRequestPermissionsResult可以打开摄像头了！！！");
        }

        if (!permissionGetted) {
            Toast.makeText(this, "请授予必要权限", Toast.LENGTH_SHORT).show();
        } else {
            printCameraInfo();
        }
    }

}